<template>
  <div class="body_message">
    <!-- 
      当前组件是 整个消息交流组件的 根组件
      在当前组件 与 后端 建立 websocket连接
    -->
    <div class="body_message_content">

      <!-- 这是一个消息对话列表 -->
      <div class='left_box'>
        <div class="span_box"><div class="span"><span>近期消息</span></div></div>
        <div class='message_list_content' >
          <el-scrollbar>
          <el-container direction="vertical">
            <mlItem class='ml_item' v-for="item in dialog_list" 
              :key="item.dialId" 
              :item_data='item' 
              :clickedItemDialId="clickedItemDialId"
              @clickItem="handlerClickItem" 
              @deleteRelation="handlerDeleteRelation"></mlItem>
          </el-container>
          </el-scrollbar>
        </div>
        
      </div>
    
      <div class='right_box'>
        <!-- v-show="this.you_data.dialId != 0" -->
        <div>
          <!-- 这是一个具体与某个用户的聊天界面 -->
          <mDetail :you_data="you_data" 
            :websocket="websocket"
            :new_message="new_message" 
            :changeNewContent="changeNewContent"
            ></mDetail>
        </div>
        <!-- <div v-show='this.you_data.dialId == 0'>
          选择一个人开始聊天吧
        </div> -->
      
      </div>
    </div>
  </div>
</template>

<script>
import mlItem from "./message-list-item"
import mDetail from './message-detail'
export default {
  components: {
    mlItem,
    mDetail,
  },
   // 建立websocket连接，获取对话列表
  mounted() {
    
    this.createWebSocket();

    this.getMoreRelation();
    
  }, 
  
  computed:{  },
  watch:{
    new_message:{ // 监视 其他人传递来的消息
      handler: function(newValue){
        console.log("watch: 收到新消息", newValue)
        var dialId = newValue.dialogId;
        this.changeNewContent(dialId, newValue.content);
      },
      deep: true,
    },
    you_data:{
      handler: function(newValue){
        console.log("list:you_data发生修改",newValue)
        // 这里要 清除未读 标记
        var dialId = newValue.dialId;
        var index = this.getDialogRelationByDialogId(dialId);
        if(index == -1){
          return;
        }
        this.dialog_list[index].unreadNum = 0;
        console.log("清除unreadNum", this.dialog_list[index]);
      }
    },
  },
  data() {
    return {
      clickedItemDialId: -1,
      websocket: null,
      you_data:{
        dialId: 0,
        uid: 0,
        nickName: '',
        portrait: '',
      },
      new_message:{
        "dialogId":0,"sendUid":0,"recvUid":0,"content":""
      },
      relation_page:{
        page: '1',
        limit: '10',
        sidx: 'new_time', 
        order: 'desc', 
        key: '',
      },
      realtion_page_back:{
        "totalCount":0,
        "pageSize":5,
        "totalPage":2,
        "currPage":1
      },
      // 维持所有的 对话列表 信息，这些信息到时候都从 后端 获取。
      dialog_list:[
      /*{
        dialId: 1,
        // user_send: ,
        // user_recv: ,
        uid: 1,
        nickName: "壹号",
        portrait: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png', 
        // unread_id: ,
        unreadNum: 0,
      },{
        dialId: 2,
        uid: 2,
        nickName: "二号",
        portrait: '', 
        unreadNum: 3,
      },{
        dialId: 3,
        uid: 3,
        nickName: "叁号",
        portrait: '', 
        unreadNum: 12,
      }*/
      ],


    }
  },
  methods: {
    // 选择某个 dialogRelation 后，获取 dialogDetail
    handlerClickItem( data ){
      // console.log("list组件监听到item组件：", data )
      this.you_data = data
      this.clickedItemDialId = data.dialId
    },
    resetYouData(){
      this.you_data = {
        dialId: 0,
        uid: 0,
        nickName: '',
        portrait: '',
      }
    },
    // 删除某个 dialogRelation
    handlerDeleteRelation(_dialId){
      // console.log("handlerDeleteRelation",_dialId)
      // return;
      var index = this.getDialogRelationByDialogId(_dialId);
      this.dialog_list.splice(index, 1);
      
      this.$http1({
        url: this.$http.adornUrl(`/user/dialog/relation/delete/${_dialId}`),
        method: "post",
        // data: this.$http.adornData(data, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        // 
        console.log("deleteDilaogRelation", this.you_data, this.you_data.dialId, _dialId)
        if(this.dialog_list.length === 0){ // 删没了
          this.resetYouData()
        }
        else if(this.you_data.dialId === _dialId){
          if(index === this.dialog_list.length){
            index = 0;
          }
          var {dialId, uid, nickName, portrait} = this.dialog_list[index];
          var new_you_data = {
            dialId: dialId,
            uid: uid,
            nickName: nickName,
            portrait: portrait,
          }
          this.you_data = new_you_data;
          this.clickedItemDialId = this.you_data.dialId
        }
        
      });
    },
    // 从后端分页获取 dialogRelation
    getMoreRelation(){
      var data = this.relation_page
      // 获取所有的 信息对话 列表
      console.log("开始获取 对话列表 信息")
      this.$http1({
        url: this.$http.adornUrl(`/user/dialog/relation/${this.currentUser.user.uid}`),
        method: "post",
        data: this.$http.adornData(data, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "成功!",
        });
        this.dialog_list = data.page.list;
      });
    },
    // 获取某个具体的 dialogRelation，方便操作
    getDialogRelationByDialogId(dialId){
      for(var i = 0;i<this.dialog_list.length;i++){
        if( dialId === this.dialog_list[i].dialId){
          return i;
        }
      }
      return -1;
    },
    // 修改某个具体的 dialogReltion 的 newContent 属性
    changeNewContent(dialId, content){
      var index = this.getDialogRelationByDialogId(dialId);
      if(index == -1){
        // 发送请求获取信息（1、删了，2、没有过）
        // todo：重新获取 or 增加新的
        this.$http1({
          url: this.$http.adornUrl(`/user/dialog/relation/info/${dialId}`),
          method: "post",
        }).then(({ data }) => {
          if(data.code === 0){
            this.dialog_list.unshift(data.dialogRelation)
          }
          
        });
      }else{
        console.log("修改content",index , content)
        this.dialog_list[index].newContent = this.substring(content);
        if(this.you_data.dialId != dialId){
          this.dialog_list[index].unreadNum++;
        }
      }
    },
    // 切分字符串，保留前10个字符
    substring(str){
      if(str.length > 10){
        return str.substring(0,10);
      }
      return str;
    },
    // 与后端建立 websocket 连接
    createWebSocket(){
      console.log("准备建立websocket连接")
      // 此处建立websocket连接，即一进入聊天界面就开始
      if('WebSocket' in window){
        this.websocket = new WebSocket(
          `ws://localhost:8081/websocket/dialog/${this.currentUser.user.uid}`)
        // this.websocket = new WebSocket(
        //   `ws://localhost:8081/websocket/dialog/${this.currentUser.user.uid}`,
        //   localStorage.getItem("user_token_"+this.currentUser.user.uid))
      }else{
        console.log("Not support websocket")
      }

      this.websocket.vue = this;

      this.websocket.onopen = function(){
        console.log("websocket：建立连接成功")
      }

      this.websocket.onerror = function(){
        console.log("websocket: 建立连接失败")
      }

      this.websocket.onmessage=function(event,n1,n2,n3,n4){
        // console.log(event,n1,n2,n3,n4)
        this.vue.new_message = JSON.parse(event.data);
        console.log("list: ws收到数据",this);
      }
    },
    

    
  },
}
</script>

<style>
  .body_message{
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;

  }
  .body_message_content{
    position: relative;
    width: 100%;
    display: flex;
    /* border: 1px solid #666; */
    border-radius: 5px;
  }

  .left_box{
    /* background: rgb(124, 255, 146); */
    background: #fff;
    width: 240px;
    height: 100%;
  }
  .left_box .span_box{
    background: #fff;
    height: 36px;
  }
  .left_box .span{
    text-align: center;
    padding-top: 10px;
  }
  .right_box{
    position: absolute;
    left: 240px;
    right: 0px;
    height: 100%;
  }


    /** 左侧 list 内容 */
  .message_list_content{
    height: 500px;
  }

  .message_list_content .el-scrollbar {
      height: 80%; /** 设置显示的 原高度的多少 */
  }
  .message_list_content .el-scrollbar__wrap {
    overflow-x: hidden; /* 隐藏水平滚动条，但是还占位置 */
  }

</style>